/*
 *
 *      Copyright (c) 2018-2025, secureplat All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the pig4cloud.com developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: secureplat
 *
 */

package com.iwomy.secureplat.admin.controller;

import com.iwomy.secureplat.admin.api.entity.SysDept;
import com.iwomy.secureplat.admin.api.vo.DeptExcelVo;
import com.iwomy.secureplat.admin.api.vo.DeptVO;
import com.iwomy.secureplat.admin.service.SysDeptService;
import com.iwomy.secureplat.common.core.util.R;
import com.iwomy.secureplat.common.data.tenant.TenantContextHolder;
import com.iwomy.secureplat.common.excel.annotation.RequestExcel;
import com.iwomy.secureplat.common.excel.annotation.ResponseExcel;
import com.iwomy.secureplat.common.log.annotation.SysLog;
import com.iwomy.secureplat.common.security.annotation.Inner;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 部门管理 前端控制器
 * </p>
 *
 * @author secureplat
 * @since 2018-01-20
 */
@RestController
@AllArgsConstructor
@RequestMapping("/dept")
@Tag(description = "dept", name = "部门管理模块")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class SysDeptController {

	private final SysDeptService sysDeptService;


	/**
	 * 通过ID查询
	 *
	 * @param id ID
	 * @return SysDept
	 */
	@GetMapping("/{id}")
	public R getById(@PathVariable Long id) {
		Long tenantId = TenantContextHolder.getTenantId();
		TenantContextHolder.clear();
		SysDept sysDept = sysDeptService.getById(id);
		TenantContextHolder.setTenantId(tenantId);
		return R.ok(sysDept);
	}

	/**
	 * 通过ID查询
	 *
	 * @param id ID
	 * @return SysDept
	 */
	@GetMapping("/getExpenses/{id}")
	@Inner(value = false)
	public R getExpenses(@PathVariable Long id) {
		TenantContextHolder.clear();
		SysDept sysDept = sysDeptService.getById(id);
		return R.ok(sysDept);
	}

	/**
	 * 通过ID查询
	 *
	 * @return SysDept
	 */
	@GetMapping("/getByIds/{ids}")
	public R getByIds(@PathVariable List<Long> ids) {
		List<SysDept> deptList = sysDeptService.listByIds(ids);
		List<DeptVO> deptInfoList = new ArrayList<>();
		for (SysDept dept : deptList) {
			DeptVO deptInfo = new DeptVO();
			deptInfo.setDeptId(dept.getDeptId());
			deptInfo.setDeptName(dept.getName());
			deptInfoList.add(deptInfo);
		}
		return R.ok(deptInfoList);
	}

	/**
	 * 查询全部部门
	 */
	@GetMapping("/getAllDeptList")
	public R getAllDeptList(@RequestParam("deptName") String deptName) {
		return R.ok(sysDeptService.getAllDeptList(deptName));
	}

	/**
	 * 查询全部部门
	 */
	@GetMapping("/list")
	public R list() {
		return R.ok(sysDeptService.list());
	}

	/**
	 * 返回树形菜单集合
	 *
	 * @param deptName 部门名称
	 * @return 树形菜单
	 */
	@GetMapping(value = "/tree")
	public R getTree(String deptName, Long parentId) {
		return R.ok(sysDeptService.selectTree(deptName, parentId));
	}

	/**
	 * 添加
	 *
	 * @param sysDept 实体
	 * @return success/false
	 */
	@SysLog("添加部门")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('sys_dept_add')")
	public R save(@Valid @RequestBody SysDept sysDept) {
		return R.ok(sysDeptService.save(sysDept));
	}

	/**
	 * 删除
	 *
	 * @param id ID
	 * @return success/false
	 */
	@SysLog("删除部门")
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('sys_dept_del')")
	public R removeById(@PathVariable Long id) {
		return R.ok(sysDeptService.removeDeptById(id));
	}

	/**
	 * 编辑
	 *
	 * @param sysDept 实体
	 * @return success/false
	 */
	@SysLog("编辑部门")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('sys_dept_edit')")
	public R update(@Valid @RequestBody SysDept sysDept) {
		sysDept.setUpdateTime(LocalDateTime.now());
		return R.ok(sysDeptService.updateById(sysDept));
	}

	@SysLog("编辑部门")
	@PutMapping("/remote")
	public R remote(@Valid @RequestBody SysDept sysDept) {
		sysDept.setUpdateTime(LocalDateTime.now());
		return R.ok(sysDeptService.updateById(sysDept));
	}

	/**
	 * 查收子级列表
	 *
	 * @return 返回子级
	 */
	@GetMapping(value = "/getDescendantList/{deptId}")
	public R getDescendantList(@PathVariable Long deptId) {
		return R.ok(sysDeptService.listDescendant(deptId));
	}

	/**
	 * 查收子级列表
	 *
	 * @return 返回子级
	 */
	@GetMapping(value = "/getChildrenList")
	public R getChildrenList(@RequestParam("deptIds") Long[] deptIds) {
		List<SysDept> resultList = new ArrayList<>();
		for (Long deptId : deptIds) {
			List<SysDept> descendantList = sysDeptService.listDescendant(deptId);
			resultList.addAll(descendantList);
		}
		return R.ok(resultList);
	}

	@GetMapping(value = "/leader/{deptId}")
	public R getAllDeptLeader(@PathVariable Long deptId) {
		return R.ok(sysDeptService.listDeptLeader(deptId));
	}

	/**
	 * 导出部门
	 *
	 * @return
	 */
	@ResponseExcel
	@GetMapping("/export")
	public List<DeptExcelVo> export() {
		return sysDeptService.listExcelVo();
	}

	/**
	 * 导入部门
	 *
	 * @param excelVOList
	 * @param bindingResult
	 * @return
	 */
	@PostMapping("import")
	public R importDept(@RequestExcel List<DeptExcelVo> excelVOList, BindingResult bindingResult) {
		return sysDeptService.importDept(excelVOList, bindingResult);
	}

	/**
	 * 通过ID查询部门是否可授权
	 *
	 * @return SysDept
	 */
	@GetMapping("/authorize/{deptId}")
	public R getAuthorizeById(@PathVariable Long deptId) {
		return sysDeptService.getAuthorizeById(deptId);
	}

	/**
	 * 查询全部部门
	 */
	@GetMapping("/listByDeptId/{id}")
	public R listByDeptId(@PathVariable("id") Long id) {
		return R.ok(sysDeptService.listByDeptId(id));
	}

	/**
	 * 通过部门名查询部门id
	 */
	@GetMapping("/getDeptId")
	R getDeptId(@RequestParam("deptName") String deptName) {
		return R.ok(sysDeptService.getDeptId(deptName));
	}

	/**
	 * 查询全部部门
	 */
	@GetMapping("/map")
	public R map() {
		List<SysDept> list = sysDeptService.list();
		Map<Long, SysDept> collect = list.stream().collect(Collectors.toMap(SysDept::getDeptId, sysDept -> sysDept));
		return R.ok(collect);
	}

	/**
	 * 查询单位层级
	 */
	@GetMapping(value = "/getListAncestor/{deptId}")
	public R getListAncestor(@PathVariable Long deptId) {
		return R.ok(sysDeptService.listAncestor(deptId));
	}


}
